﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YJKArchUtils.Previewer;
using YJKArchUtils.StructurePoleSuit;
using YJKArchUtils.Utils;
using YJKRevitKernel.TransformUtility;

namespace YJKRevitColumn.ColumnModule
{
	public partial class ImportSettingForm : System.Windows.Forms.Form
	{
		public string FamilyName
		{
			get
			{
				return this.tbFamilyName.Text;
			}
		}

		public Material ColumnMaterial
		{
			get
			{
				return this.m_materials[this.cmbMaterial.SelectedIndex];
			}
		}

		public new Level TopLevel
		{
			get
			{
				return this.GetCurLevel(this.m_doc);
			}
		}

		public List<List<Curve>> ProfileCurves(ref List<Curve> centerCurveList)
		{
			List<List<Curve>> result = new List<List<Curve>>();
			List<KeyValuePair<string, Curve>> list = new List<KeyValuePair<string, Curve>>();
			List<KeyValuePair<string, Curve>> list2 = new List<KeyValuePair<string, Curve>>();
			this.m_ProfileSearcher.GetEdgeLoopsByEdgeList(ref result, ref list, ref list2);
			foreach (KeyValuePair<string, Curve> keyValuePair in list)
			{
				centerCurveList.Add(keyValuePair.Value);
			}
			foreach (KeyValuePair<string, Curve> keyValuePair2 in list2)
			{
				centerCurveList.Add(keyValuePair2.Value);
			}
			return result;
		}

		public ImportSettingForm(ExternalCommandData cmdData, List<ColumnProfilePart> partList, XYZ selecetBoxMin, XYZ selecetBoxMax, List<Material> materials)
		{
			this.m_Revit = cmdData;
			this.m_doc = cmdData.Application.ActiveUIDocument.Document;
			this.m_materials = materials;
			this.m_ProfileSearcher = new ColumnLoopSearcher(cmdData, partList, false, selecetBoxMin, selecetBoxMax, null, false);
			this.InitializeComponent();
			this.InitializeData();
			this.m_MinWallThickness = double.MaxValue;
			foreach (ColumnProfilePart columnProfilePart in partList)
			{
				double num = columnProfilePart.NegativeHalfWidth + columnProfilePart.PositiveHalfWidth;
				if (Geometry.LessThan(num, this.m_MinWallThickness))
				{
					this.m_MinWallThickness = num;
				}
			}
			int num2 = this.tbFamilyName.Height / 5;
			this.m_Previewer = new FormPreviewer(this, num2, this.cmbBaseOffset.Bottom + num2, this.DGVPartLength.Width, this.DGVPartLength.Height, 1u);
			base.MouseWheel += this.m_Previewer.MouseWheel;
		}

		public void InitializeData()
		{
			this.tbFamilyName.Text = this.GetFamilyName();
			this.InitalizeLevelInfos();
			this.m_CurrentPartList = this.m_ProfileSearcher.GetCurrentEndPartList();
			this.m_CurrentPartList.Sort((ColumnProfilePart left, ColumnProfilePart right) => left.Number.CompareTo(right.Number));
			for (int i = 0; i < this.m_CurrentPartList.Count; i++)
			{
				DataGridViewRow dataGridViewRow = new DataGridViewRow();
				this.m_CurrentPartList[i].Number = i + 1;
				DataGridViewTextBoxCell dataGridViewTextBoxCell = new DataGridViewTextBoxCell();
				dataGridViewTextBoxCell.Value = this.m_CurrentPartList[i].Number.ToString();
				dataGridViewRow.Cells.Add(dataGridViewTextBoxCell);
				int num = (int)(Common.FeetToMM(this.m_CurrentPartList[i].ExtendLength) * 10.0 + 0.5) / 10;
				DataGridViewTextBoxCell dataGridViewTextBoxCell2 = new DataGridViewTextBoxCell();
				dataGridViewTextBoxCell2.Value = num.ToString();
				dataGridViewRow.Cells.Add(dataGridViewTextBoxCell2);
				DataGridViewTextBoxCell dataGridViewTextBoxCell3 = new DataGridViewTextBoxCell();
				dataGridViewTextBoxCell3.Value = this.GetColumnWidth(this.m_CurrentPartList[i], false).ToString();
				dataGridViewRow.Cells.Add(dataGridViewTextBoxCell3);
				DataGridViewTextBoxCell dataGridViewTextBoxCell4 = new DataGridViewTextBoxCell();
				dataGridViewTextBoxCell4.Value = this.GetColumnWidth(this.m_CurrentPartList[i], true).ToString();
				dataGridViewRow.Cells.Add(dataGridViewTextBoxCell4);
				DataGridViewCheckBoxCell dataGridViewCheckBoxCell = new DataGridViewCheckBoxCell();
				dataGridViewCheckBoxCell.Value = this.m_CurrentPartList[i].Checked.ToString();
				dataGridViewRow.Cells.Add(dataGridViewCheckBoxCell);
				this.DGVPartLength.Rows.Add(dataGridViewRow);
			}
			this.cmbMaterial.Items.Clear();
			foreach (Material material in this.m_materials)
			{
				this.cmbMaterial.Items.Add(material.Name);
			}
			this.cmbMaterial.SelectedIndex = 0;
			string text = "当前层高,2700,2800,2900,3000,3300,3600,3900,4200,5100,5400";
			this.m_lstHeight.AddRange(text.Split(new char[]
			{
				','
			}));
			foreach (string item in this.m_lstHeight)
			{
				this.cmbHeight.AddItem(item);
			}
			this.cmbHeight.SelectedIndex = 0;
			text = "300,250,200,150,100,50,0,-50,-100,-150,-200,-250,-300";
			this.m_lstBaseOffset.AddRange(text.Split(new char[]
			{
				','
			}));
			foreach (string item2 in this.m_lstBaseOffset)
			{
				this.cmbBaseOffset.AddItem(item2);
			}
			this.cmbBaseOffset.SelectedIndex = 6;
		}

		private Level GetCurLevel(Autodesk.Revit.DB.Document doc)
		{
			ElementId eleId = this.m_doc.ActiveView.GenLevel.Id;
			if (this.m_sortLevels.Count == 0)
			{
				this.m_sortLevels = Common.GetSortLevels(doc, double.MinValue, double.MaxValue);
			}
			int num = this.m_sortLevels.FindIndex((Level level) => eleId == level.Id);
			if (num != -1 && num < this.m_sortLevels.Count - 1)
			{
				return this.m_sortLevels[num + 1];
			}
			return null;
		}

		private int GetColumnWidth(ColumnProfilePart columnInfo, bool bPositive)
		{
			Line line = Line.CreateBound(columnInfo.StartPoint, columnInfo.EndPoint);
			if (bPositive)
			{
				XYZ xyz = (columnInfo.PositiveEndPoint + columnInfo.PositiveStartPoint) / 2.0;
				return Convert.ToInt32(AssistFunc.feetToMM(line.Project(xyz).Distance));
			}
			XYZ xyz2 = (columnInfo.NegativeEndPoint + columnInfo.NegativeStartPoint) / 2.0;
			return Convert.ToInt32(AssistFunc.feetToMM(line.Project(xyz2).Distance));
		}

		private void InitalizeLevelInfos()
		{
			double elevation = this.m_Revit.Application.ActiveUIDocument.ActiveView.GenLevel.Elevation;
			double val = 10000.0;
			IEnumerable<Element> enumerable = new FilteredElementCollector(this.m_Revit.Application.ActiveUIDocument.Document).OfClass(typeof(Level)).ToElements();
			int num = 0;
			foreach (Element element in enumerable)
			{
				Level level = element as Level;
				if (level != null)
				{
					double elevation2 = level.Elevation;
					if (!Geometry.IsEqual(elevation2, elevation) && Geometry.Greaterthan_Or_Equal(elevation2 - elevation, 0.0) && Geometry.LessThan(elevation2 - elevation, val))
					{
						val = elevation2 - elevation;
					}
					this.m_LevelList.Add(level);
					num++;
				}
			}
		}

		protected override void DefWndProc(ref Message m)
		{
			int msg = m.Msg;
			if (msg == 1125)
			{
				if (m.WParam.ToInt32() == 1)
				{
					List<List<Curve>> list = new List<List<Curve>>();
					List<KeyValuePair<string, Curve>> showCenterCurve = new List<KeyValuePair<string, Curve>>();
					List<KeyValuePair<string, Curve>> hideCenterCurve = new List<KeyValuePair<string, Curve>>();
					this.m_ProfileSearcher.GetEdgeLoopsByEdgeList(ref list, ref showCenterCurve, ref hideCenterCurve);
					List<Curve> list2 = new List<Curve>();
					foreach (List<Curve> collection in list)
					{
						list2.AddRange(collection);
					}
					ColumnProfilePlotter columnProfilePlotter = new ColumnProfilePlotter(list2, showCenterCurve, hideCenterCurve, this.m_MinWallThickness);
					try
					{
						columnProfilePlotter.Draw(PenColor.PC_Gray, PenColor.PC_Black, PenColor.PC_Black);
					}
					catch (Exception)
					{
					}
					this.m_Previewer.Curves = columnProfilePlotter.Curves;
					this.m_Previewer.TextNotes = columnProfilePlotter.Texts;
					return;
				}
			}
			else
			{
				base.DefWndProc(ref m);
			}
		}

		private void DGVPartLength_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			try
			{
				if (this.DGVPartLength.CurrentCell.ColumnIndex == 4)
				{
					int rowIndex = this.DGVPartLength.CurrentCell.RowIndex;
					DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)this.DGVPartLength.CurrentCell;
					bool flag = Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue);
					if (!flag)
					{
						if (this.m_CurrentPartList.Count < 3)
						{
							dataGridViewCheckBoxCell.EditingCellFormattedValue = !flag;
							YJKMessageBox.Show("至少选择两个墙体");
							dataGridViewCheckBoxCell.Value = !flag;
							return;
						}
						int num = 0;
						using (List<ColumnProfilePart>.Enumerator enumerator = this.m_CurrentPartList.GetEnumerator())
						{
							while (enumerator.MoveNext())
							{
								if (enumerator.Current.Checked)
								{
									num++;
								}
							}
						}
						if (num < 3)
						{
							dataGridViewCheckBoxCell.EditingCellFormattedValue = !flag;
							YJKMessageBox.Show("至少选择两个墙体");
							dataGridViewCheckBoxCell.Value = !flag;
							return;
						}
					}
					this.m_CurrentPartList[rowIndex].Checked = flag;
					this.m_ProfileSearcher.SetChecked(this.m_CurrentPartList[rowIndex].ComponentId, flag);
					this.Refresh();
				}
			}
			catch (Exception)
			{
			}
		}

		private void DGVPartLength_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
		{
			System.Windows.Forms.TextBox textBox = e.Control as System.Windows.Forms.TextBox;
			if (textBox != null)
			{
				textBox.TextChanged += this.DGVPartLengthTextChanged;
				textBox.LostFocus += this.DGVPartLengthLostFocus;
			}
		}

		private void DGVPartLengthLostFocus(object sender, EventArgs e)
		{
		}

		private void DGVPartLengthTextChanged(object sender, EventArgs e)
		{
			if (this.DGVPartLength.CurrentCell.ColumnIndex == 1)
			{
				int rowIndex = this.DGVPartLength.CurrentCell.RowIndex;
				string text = ((System.Windows.Forms.TextBox)sender).Text;
				int num = 0;
				try
				{
					num = Convert.ToInt32(text);
				}
				catch (Exception)
				{
					((System.Windows.Forms.TextBox)sender).Text = Common.FeetToMM(this.m_CurrentPartList[rowIndex].ExtendLength).ToString();
					return;
				}
				if (Geometry.IsEqual(this.m_CurrentPartList[rowIndex].ExtendLength, (double)num))
				{
					return;
				}
				if (num <= 0 || num > 10000)
				{
					((System.Windows.Forms.TextBox)sender).Text = Common.FeetToMM(this.m_CurrentPartList[rowIndex].ExtendLength).ToString();
					YJKMessageBox.Show("输入长度超出范围：大于零小于10000mm");
					return;
				}
				double newLength = Common.MMToFeet((double)num);
				this.m_ProfileSearcher.ResetLength(this.m_CurrentPartList[rowIndex].ComponentId, newLength);
				this.m_CurrentPartList[rowIndex].ExtendLength = this.m_ProfileSearcher.GetLength(this.m_CurrentPartList[rowIndex].ComponentId);
				this.Refresh();
				return;
			}
			else if (this.DGVPartLength.CurrentCell.ColumnIndex == 2 || this.DGVPartLength.CurrentCell.ColumnIndex == 3)
			{
				int num2 = Convert.ToInt32(this.DGVPartLength.CurrentCell.Value);
				int rowIndex2 = this.DGVPartLength.CurrentCell.RowIndex;
				string text2 = ((System.Windows.Forms.TextBox)sender).Text;
				int num3 = 0;
				try
				{
					num3 = Convert.ToInt32(text2);
				}
				catch (Exception)
				{
					((System.Windows.Forms.TextBox)sender).Text = num2.ToString();
					return;
				}
				if (Geometry.IsEqual((double)num2, (double)num3))
				{
					return;
				}
				if (num3 < 0 || num3 > 10000)
				{
					((System.Windows.Forms.TextBox)sender).Text = num2.ToString();
					YJKMessageBox.Show("输入宽度超出范围：大于等于零小于10000mm");
					return;
				}
				if (this.DGVPartLength.CurrentCell.ColumnIndex == 2)
				{
					if (Convert.ToInt32(this.DGVPartLength.Rows[rowIndex2].Cells[3].Value) == 0 && ((System.Windows.Forms.TextBox)sender).Text.Equals("0"))
					{
						((System.Windows.Forms.TextBox)sender).Text = num2.ToString();
						YJKMessageBox.Show("输入宽度不能同时为0");
						return;
					}
				}
				else if (Convert.ToInt32(this.DGVPartLength.Rows[rowIndex2].Cells[2].Value) == 0 && ((System.Windows.Forms.TextBox)sender).Text.Equals("0"))
				{
					((System.Windows.Forms.TextBox)sender).Text = num2.ToString();
					YJKMessageBox.Show("输入宽度不能同时为0");
					return;
				}
				if (this.DGVPartLength.CurrentCell.ColumnIndex == 2)
				{
					this.SetColumnBoundaryPositivePoints(num3, this.m_CurrentPartList[rowIndex2]);
				}
				else
				{
					this.SetColumnBoundaryNegativePoints(num3, this.m_CurrentPartList[rowIndex2]);
				}
				this.Refresh();
			}
		}

		private void SetColumnBoundaryPositivePoints(int nWidth, ColumnProfilePart column)
		{
			Line line = Line.CreateBound(column.StartPoint, column.EndPoint);
			XYZ xyz = (column.PositiveEndPoint + column.PositiveStartPoint) / 2.0;
			XYZ xyzpoint = line.Project(xyz).XYZPoint;
			XYZ xyz2 = (xyz - xyzpoint).Normalize();
			if (xyz2.IsAlmostEqualTo(XYZ.Zero))
			{
				xyz2 = Geometry.RotateTo(line.Direction, Math.PI*.5, line.GetEndPoint(0) + line.GetEndPoint(1) / 2.0).Normalize();
			}
			XYZ xyzpoint2 = line.Project(column.PositiveEndPoint).XYZPoint;
			XYZ xyzpoint3 = line.Project(column.PositiveStartPoint).XYZPoint;
			if (nWidth == 0)
			{
				column.PositiveEndPoint = xyzpoint2;
				column.PositiveStartPoint = xyzpoint3;
				return;
			}
			Transform transform = Transform.CreateTranslation(xyz2 * AssistFunc.mmToFeet((double)nWidth));
			column.PositiveEndPoint = TransformUtilityMethod.TransformPoint(xyzpoint2, transform);
			column.PositiveStartPoint = TransformUtilityMethod.TransformPoint(xyzpoint3, transform);
		}

		private void SetColumnBoundaryNegativePoints(int nWidth, ColumnProfilePart column)
		{
			Line line = Line.CreateBound(column.StartPoint, column.EndPoint);
			XYZ xyz = (column.NegativeEndPoint + column.NegativeStartPoint) / 2.0;
			XYZ xyzpoint = line.Project(xyz).XYZPoint;
			XYZ xyz2 = (xyz - xyzpoint).Normalize();
			if (xyz2.IsAlmostEqualTo(XYZ.Zero))
			{
				xyz2 = Geometry.RotateTo(line.Direction, -Math.PI*.5, line.GetEndPoint(0) + line.GetEndPoint(1) / 2.0).Normalize();
			}
			XYZ xyzpoint2 = line.Project(column.NegativeEndPoint).XYZPoint;
			XYZ xyzpoint3 = line.Project(column.NegativeStartPoint).XYZPoint;
			if (nWidth == 0)
			{
				column.NegativeEndPoint = xyzpoint2;
				column.NegativeStartPoint = xyzpoint3;
				return;
			}
			Transform transform = Transform.CreateTranslation(xyz2 * AssistFunc.mmToFeet((double)nWidth));
			column.NegativeEndPoint = TransformUtilityMethod.TransformPoint(xyzpoint2, transform);
			column.NegativeStartPoint = TransformUtilityMethod.TransformPoint(xyzpoint3, transform);
		}

		private void ImportSettingForm_Load(object sender, EventArgs e)
		{
			this.LoadCompornentData();
		}

		private void ImportSettingForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (base.DialogResult == DialogResult.OK)
			{
				string text = this.tbFamilyName.Text;
				if (text.CompareTo("") == 0)
				{
					YJKMessageBox.Show("族名称不能为空！");
					e.Cancel = true;
					return;
				}
				if (this.FindedColumnFamily(text))
				{
					YJKMessageBox.Show("该族名称已经存在，请重新命名！");
					e.Cancel = true;
					return;
				}
				this.SaveCompornentData();
			}
		}

		private bool FindedColumnFamily(string familyName)
		{
			foreach (Element element in new FilteredElementCollector(this.m_Revit.Application.ActiveUIDocument.Document).OfClass(typeof(Family)).ToElements())
			{
				Family family = element as Family;
				if (family != null)
				{
					Category familyCategory = RevitVersionFuncs.GetFamilyCategory(family);
					if (familyCategory != null && -2000100 == familyCategory.Id.IntegerValue && familyName.ToUpper().CompareTo(family.Name.ToUpper()) == 0)
					{
						return true;
					}
				}
			}
			return false;
		}

		private string GetFamilyName()
		{
			string text = "角柱";
			List<int> list = new List<int>();
			foreach (Element element in new FilteredElementCollector(this.m_Revit.Application.ActiveUIDocument.Document).OfClass(typeof(Family)).ToElements())
			{
				Family family = element as Family;
				if (family != null)
				{
					Category familyCategory = RevitVersionFuncs.GetFamilyCategory(family);
					if (familyCategory != null && -2001330 == familyCategory.Id.IntegerValue)
					{
						string name = family.Name;
						if (name.IndexOf(text) != -1)
						{
							try
							{
								int item = Convert.ToInt32(name.Substring(text.Length, name.Length - text.Length));
								list.Add(item);
							}
							catch (Exception)
							{
							}
						}
					}
				}
			}
			list.Sort();
			int num = 1;
			if (list.Count > 0)
			{
				num = list[list.Count - 1] + 1;
			}
			return text + num.ToString();
		}

		private void LoadCompornentData()
		{
			string path = Product.UserDataLocation + "\\" + "ImportColumnSettingForm.dat";
			if (!File.Exists(path))
			{
				return;
			}
			FileStream fileStream = new FileStream(path, FileMode.Open);
			StreamReader streamReader = new StreamReader(fileStream);
			streamReader.BaseStream.Seek(0L, SeekOrigin.Begin);
			string text = streamReader.ReadLine();
			if (text.Equals(string.Empty) || text == null)
			{
				text = "当前层高";
			}
			this.cmbHeight.Text = text;
			string text2 = streamReader.ReadLine();
			if (text2.Equals(string.Empty) || text2 == null)
			{
				text2 = "0";
			}
			this.cmbBaseOffset.Text = text2;
			streamReader.Close();
			fileStream.Close();
		}

		private void SaveCompornentData()
		{
			FileStream fileStream = new FileStream(Product.UserDataLocation + "\\" + "ImportColumnSettingForm.dat", FileMode.Create);
			StreamWriter streamWriter = new StreamWriter(fileStream);
			streamWriter.WriteLine(this.cmbHeight.Text);
			streamWriter.WriteLine(this.cmbBaseOffset.Text);
			streamWriter.Flush();
			streamWriter.Close();
			fileStream.Close();
		}

		private void DGVPartLength_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			try
			{
				if (this.DGVPartLength.CurrentCell.ColumnIndex == 2)
				{
					DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)this.DGVPartLength.CurrentCell;
					bool flag = Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue);
					dataGridViewCheckBoxCell.EditingCellFormattedValue = !flag;
					int rowIndex = this.DGVPartLength.CurrentCell.RowIndex;
					this.m_CurrentPartList[rowIndex].Checked = flag;
					this.m_ProfileSearcher.SetChecked(this.m_CurrentPartList[rowIndex].ComponentId, flag);
					this.Refresh();
				}
			}
			catch (Exception)
			{
			}
		}

		private void DGVPartLength_CurrentCellDirtyStateChanged(object sender, EventArgs e)
		{
			this.DGVPartLength.CommitEdit(DataGridViewDataErrorContexts.Commit);
		}

		private void cmbHeight_KeyPress(object sender, KeyPressEventArgs e)
		{
			ImportSettingForm.JudgeInputData(e);
		}

		private void cmbBaseOffset_KeyPress(object sender, KeyPressEventArgs e)
		{
			ImportSettingForm.JudgeInputData(e);
		}

		private static void JudgeInputData(KeyPressEventArgs e)
		{
			if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '-' && e.KeyChar != '\b')
			{
				e.Handled = true;
				return;
			}
		}

		private ExternalCommandData m_Revit;

		private ColumnLoopSearcher m_ProfileSearcher;

		private List<ColumnProfilePart> m_CurrentPartList = new List<ColumnProfilePart>();

		private FormPreviewer m_Previewer;

		private double m_MinWallThickness;

		private List<Material> m_materials;

		private List<Level> m_LevelList = new List<Level>();

		private Document m_doc;

		private List<Level> m_sortLevels = new List<Level>();

		private List<string> m_lstHeight = new List<string>();

		private List<string> m_lstBaseOffset = new List<string>();
	}
}
